//
//  ControlPanelView.m
//  GJDigitalSDK
//
//  Created by wbb on 2021/11/9.
//

#import "ControlPanelView.h"
#import "DigitalConfig.h"
#import <AVFoundation/AVFoundation.h>
#import "DigitalMessage.h"

@interface ControlPanelView () <UITextFieldDelegate,AVAudioRecorderDelegate,AVAudioPlayerDelegate>{
    
    AVAudioRecorder *recorder;
    AVAudioPlayer *player;
    /** 录音计时器 */
//    NSTimer *recordTimer;
//    /** 播放计时器 */
//    NSTimer *playTimer;
//    /** 录音时间 */
//    NSInteger recordSecond;
//    /** 录音分钟时间 */
//    NSInteger minuteRecord;
//    /** 播放时间 */
//    NSInteger playSecond;
//    /** 播放分钟时间 */
//    NSInteger minutePlay;
    /** caf文件路径 */
    NSURL *tmpUrl;
}
@property (weak, nonatomic) IBOutlet UITextField *contentTF;
@property (weak, nonatomic) IBOutlet UIButton *sendBtn;
@property (weak, nonatomic) IBOutlet UIView *wavBackView;
@property (weak, nonatomic) IBOutlet UIButton *wavBtn1;
@property (weak, nonatomic) IBOutlet UIButton *wavbtn2;
@property (weak, nonatomic) IBOutlet UILabel *longLab;


@end
@implementation ControlPanelView

- (void)awakeFromNib {
    [super awakeFromNib];
    self.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0];
    
    self.contentTF.delegate = self;
    self.longLab.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *rec = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longEvent:)];
    rec.minimumPressDuration = 0.5;
    [self.longLab addGestureRecognizer:rec];

    if ([[DigitalConfig shareConfig].robotMode isEqualToString:@"bot"]) {
        self.wavBackView.hidden = YES;
    }
    
    self.longLab.hidden = [DigitalConfig shareConfig].isAsr;
}
- (IBAction)sendEvent:(UIButton *)sender {
    if(self.sendBlock) {
        self.sendBlock();
    }
}
- (IBAction)wavEvent:(UIButton *)sender {
    if (sender == self.wavBtn1) {
        if (self.wavBackView) {
            self.wavChooseBlock(WAV1_ENUM);
        }
    }else if (sender == self.wavbtn2) {
        if (self.wavBackView) {
            self.wavChooseBlock(WAV2_ENUM);
        }
    }
}
- (IBAction)cancel:(UIButton *)sender {
    self.hidden = YES;
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}
- (void)longEvent:(UIGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        if (self.longPressBlock) {
            self.longPressBlock(LONG_PRESS_BEGIN);
            [self recordingAction];
        }
        
        AudioServicesPlaySystemSound(1520);
    }else if (gesture.state == UIGestureRecognizerStateEnded) {
        if (self.longPressBlock) {
            self.longPressBlock(LONG_PRESS_END);
        }
        
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (self.contentBlock) {
        self.contentBlock(textField.text);
    }
}

/// MARK: ============= 录音 ================

/**
 开始录音
 */
- (void)recordingAction {
    
    NSLog(@"开始录音");
//    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
//    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
//    [audioSession setActive:YES error:nil];
    //录音设置
    NSMutableDictionary *recordSettings = [[NSMutableDictionary alloc] init];
    //录音格式
    [recordSettings setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey: AVFormatIDKey];
    //采样率
    [recordSettings setValue :[NSNumber numberWithFloat:11025.0] forKey: AVSampleRateKey];
    //通道数
    [recordSettings setValue :[NSNumber numberWithInt:2] forKey: AVNumberOfChannelsKey];
    //线性采样位数
    [recordSettings setValue :[NSNumber numberWithInt:16] forKey: AVLinearPCMBitDepthKey];
    //音频质量,采样质量
    [recordSettings setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];
    
    NSError *error = nil;
    // 沙盒目录Documents地址
    NSString *recordUrl = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // caf文件路径
    tmpUrl = [NSURL URLWithString:[recordUrl stringByAppendingPathComponent:@"selfRecord.wav"]];
    //从路径下检查是否有文件
    NSData *audioData = [NSData dataWithContentsOfFile:[tmpUrl path] options: 0 error:&error];
    if(audioData)
    {
    //如果有使用文件管理移除上一次录音文件
        NSFileManager *fm = [NSFileManager defaultManager];
        [fm removeItemAtPath:[tmpUrl path] error:&error];
    }

    recorder = [[AVAudioRecorder alloc]initWithURL:tmpUrl settings:recordSettings error:&error];
    
    if (recorder) {
        //启动或者恢复记录的录音文件
        if ([recorder prepareToRecord] == YES) {
            [recorder record];
        }
        
    }else {
        NSLog(@"录音创建失败");
    }
}
/**
 停止录音
 */
- (void)stopAction {
    
    NSLog(@"停止录音");
    //停止录音
    [recorder stop];
    recorder = nil;
//    [recordTimer invalidate];
//    recordTimer = nil;
    
}

/// MARK: ============= end ================
@end
